package org.jeecg.modules.m3rd.impl;

import java.util.HashMap;
import java.util.Map;

import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.m3rd.Sso3rd;
import org.jeecg.modules.m3rd.Sso3rdProcessor;
import org.jeecg.modules.m3rd.common.Sso3rdConsts;
import org.jeecg.modules.system.mapper.SysConfigMapper;
import org.jeecg.modules.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class Sso3rdProcessorImpl implements Sso3rdProcessor {

	@Autowired
	private ISysConfigService sysConfigService;

	@Autowired
	private SysConfigMapper sysConfigMapper;

	@Autowired
	private Map<String, Sso3rd> sso3rds = new HashMap<String, Sso3rd>();

	@Override
	public Result<String> doSso3rdProcessor(String username, String password) {
		Result<String> result = new Result<String>();

		Map<String, String> sssParams = null;
		String ssoPrefix = null;
		try {
			String sso3rdServiceName = sysConfigMapper.queryConfigByCode("sso3rd");
			if (null == sso3rdServiceName || sso3rdServiceName.trim().isEmpty()) {
				log.info("none sso, username={}", username);
				result.setResult(Sso3rdConsts.SSO3RD_NONE);
				return result;
			}
			sso3rdServiceName = sso3rdServiceName.trim();
			Sso3rd sso3rd = sso3rds.get(sso3rdServiceName);
			if (null == sso3rd) {
				log.error("null == sso3rd");
				result.setResult(Sso3rdConsts.SSO3RD_RET_FAIL);
				return result;
			}
			log.info("3rd sso service, sso3rd={}", sso3rdServiceName);
			ssoPrefix = sso3rdServiceName;
			sssParams = sysConfigService.load3rdSsoInfo(ssoPrefix, username, password);
			result = sso3rd.doSso3rd(username, password, sssParams);
			log.info("result={}", result);
			return result;
		} catch (Exception e) {
			result.setResult(Sso3rdConsts.SSO3RD_RET_FAIL);
			log.error(e.getMessage(), e);
		}
		return result;
	}


}
